<template>
    <div class="app-container">
        <!-- 搜索条件 -->
        <el-card>
            <el-form :inline="true" :model="searchForm" class="search-form">
                <el-form-item label="时间维度" style="width: 300px;">
                    <el-select v-model="searchForm.timeDimension" placeholder="请选择时间维度">
                        <el-option label="天" :value="1" />
                        <el-option label="月" :value="2" />
                        <el-option label="年" :value="3" />
                    </el-select>
                </el-form-item>
                <el-form-item label="时间范围">
                    <el-date-picker v-model="searchForm.time" v-if="searchForm.timeDimension == 1" type='date' placeholder="选择时间"  value-format="YYYY-MM-DD"/>
                    <el-date-picker v-model="searchForm.time" v-if="searchForm.timeDimension == 2" type="month" placeholder="选择时间"  value-format="YYYY-MM"/>
                    <el-date-picker v-model="searchForm.time" v-if="searchForm.timeDimension == 3" type='year' placeholder="选择时间"  value-format="YYYY"/>
                </el-form-item>
                <el-form-item label="区域">
                    <el-select v-model="searchForm.region" placeholder="请选择区域" style="width: 300px;">
                        <el-option v-for="item in regionOptions" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="监测点">
                    <el-select v-model="searchForm.monitorId" placeholder="请选择监测点" style="width: 300px;">
                        <el-option v-for="item in monitoringPointOptions" :key="item.id" :label="item.name"
                            :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">查询</el-button>
                    <el-button @click="resetSearch">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 数据展示区 -->
        <el-row :gutter="20" class="mt-2">
            <el-col :span="8">
                <el-card style="height: 100%;">
                    <div class="title">全网压力合格率</div>
                    <div class="number">{{ qualifiedRateData.currentQualifiedRate || '--' }}%</div>
                    <div class="puls">
                        <span class="msg">环比上月</span>
                        {{ qualifiedRateData.chainMonth || '--' }}
                    </div>
                    <div class="puls">
                        <span class="msg">同比去年</span>
                        {{ qualifiedRateData.yearOverYear || '--' }}
                    </div>
                </el-card>
            </el-col>
            <el-col :span="8">
                <el-card>
                    <Echarts :option="pressureRatioOption" height="300px" />
                </el-card>
            </el-col>
            <el-col :span="8">
                <el-card>
                    <Echarts :option="pressureTrendOption" height="300px" />
                </el-card>
            </el-col>
        </el-row>

        <el-row :gutter="20" class="mt-2">
            <el-col :span="14">
                <el-card>
                    <el-table :data="tableData" style="width: 100%" v-loading="tableLoading">
                        <el-table-column prop="monitorName" label="监测点" align="center"></el-table-column>
                        <el-table-column prop="ampVal" label="压力振幅" align="center">
                            <template #default="{ row }">
                                {{ row.ampVal?.toFixed(3) || '--' }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="maxVal" label="最大压力" align="center">
                            <template #default="{ row }">
                                {{ row.maxVal?.toFixed(3) || '--' }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="minVal" label="最小压力" align="center">
                            <template #default="{ row }">
                                {{ row.minVal?.toFixed(3) || '--' }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="status" label="状态" align="center">
                            <template #default="{ row }">
                                <el-tag :type="row.status == '异常' ? 'danger' : 'success'">{{ row.status }}</el-tag>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-card>
                <el-card class="mt-2">
                    <Echarts :option="pressureFluctuationTrendOption" height="400px" />
                </el-card>
            </el-col>
            <el-col :span="10">
                <el-card style="padding: 10px 0;">
                    <div class="title">压力告警统计</div>
                    <div class="statistics">
                        <div class="item">
                            <div class="num">{{ warningData.totalCount || 0 }}</div>
                            <div class="msg">告警总数</div>
                        </div>
                        <div class="item">
                            <div class="num num2">{{ getHandledRate() }}%</div>
                            <div class="msg">处理率</div>
                        </div>
                    </div>
                    <div class="warning-levels">
                        <div class="level-item">
                            <div class="level-tag level1">一级</div>
                            <div class="level-count">{{ warningData.firstLevelCount || 0 }}</div>
                        </div>
                        <div class="level-item">
                            <div class="level-tag level2">二级</div>
                            <div class="level-count">{{ warningData.secondLevelCount || 0 }}</div>
                        </div>
                        <div class="level-item">
                            <div class="level-tag level3">三级</div>
                            <div class="level-count">{{ warningData.thirdLevelCount || 0 }}</div>
                        </div>
                    </div>
                </el-card>
                <el-card class="mt-2">
                    <Echarts :option="alertTimeOption" height="300px" />
                </el-card>
                <el-card class="mt-2">
                    <Echarts :option="alertTrendOption" height="300px" />
                </el-card>
            </el-col>
        </el-row>
    </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElLoading } from 'element-plus'
import Echarts from '@/components/ECharts'
import * as api from '@/api/dispatch/analyze/pressure_topics'
import dayjs from 'dayjs'

// 搜索表单
const searchForm = reactive({
    timeDimension: 1,
    time: '',
    region: '',
    monitorId: ''
})

// 区域下拉选项
const regionOptions = ref([])

// 监测点下拉选项
const monitoringPointOptions = ref([])

// 合格率数据
const qualifiedRateData = reactive({
    currentQualifiedRate: '',
    chainMonth: '',
    yearOverYear: '',
    qualifiedSamplePointCount: '',
    unqualifiedSamplePointCount: ''
})

// 告警统计数据
const warningData = reactive({
    totalCount: 0,
    unhandledCount: 0,
    handledCount: 0,
    firstLevelCount: 0,
    secondLevelCount: 0,
    thirdLevelCount: 0
})

// 表格数据
const tableData = ref([])
const tableLoading = ref(false)

// 压力趋势数据
const pressureTrendData = ref([])

// 压力振幅数据
const amplitudeTrendData = ref([])

// 告警分时段数据
const alarmDistributionData = ref([])

// 告警趋势数据
const alarmTrendData = ref([])

// 压力占比数据
const pressureRatioData = ref([])

// 初始化数据
onMounted(() => {
    searchForm.time = dayjs().format('YYYY-MM-DD')
    fetchRegionList()
    fetchMonitoringPointList()
    fetchAllData()
})

// 获取区域下拉列表
const fetchRegionList = async () => {
    try {
        const res = await api.getRegionList()
        regionOptions.value = res.data || []
        if (regionOptions.value.length > 0) {
            searchForm.region = regionOptions.value[0].id
        }
    } catch (error) {
        console.error('获取区域列表失败:', error)
        ElMessage.error('获取区域列表失败')
    }
}

// 获取监测点下拉列表
const fetchMonitoringPointList = async () => {
    try {
        const res = await api.getMonitoringPointList()
        monitoringPointOptions.value = res.data || []
        if (monitoringPointOptions.value.length > 0) {
            searchForm.monitorId = monitoringPointOptions.value[0].id
        }
    } catch (error) {
        console.error('获取监测点列表失败:', error)
        ElMessage.error('获取监测点列表失败')
    }
}

// 获取所有数据
const fetchAllData = async () => {
    try {
        tableLoading.value = true
        
        // 获取合格率数据
        const qualifiedRes = await api.getPressureQualifiedRate(searchForm)
        Object.assign(qualifiedRateData, qualifiedRes.data || {})
        
        // 获取压力趋势数据
        const trendRes = await api.getPressureTrend(searchForm)
        pressureTrendData.value = trendRes.data || []
        
        // 获取压力占比数据
        const ratioRes = await api.getPressureRatio(searchForm)
        pressureRatioData.value = ratioRes.data || []
        
        // 获取点位榜单数据
        const pointRes = await api.getPointTable(searchForm)
        tableData.value = pointRes.data || []
        
        // 获取告警统计数据
        const warningRes = await api.getPressureWarning()
        Object.assign(warningData, warningRes.data || {})
        
        // 获取压力振幅趋势数据
        const amplitudeRes = await api.getAmplitudeTrend(searchForm)
        amplitudeTrendData.value = amplitudeRes.data || []
        
        // 获取告警分时段数据
        const alarmDistRes = await api.getAlarmDistribution(searchForm)
        alarmDistributionData.value = alarmDistRes.data || []
        
        // 获取告警趋势数据
        const alarmTrendRes = await api.getAlarmTrend(searchForm)
        alarmTrendData.value = alarmTrendRes.data || []
        
        ElMessage.success('数据加载成功')
    } catch (error) {
        console.error('获取数据失败:', error)
        ElMessage.error('获取数据失败')
    } finally {
        tableLoading.value = false
    }
}

// 处理搜索
const handleSearch = () => {
    fetchAllData()
}

// 重置搜索
const resetSearch = () => {
    Object.assign(searchForm, {
        timeDimension: 1,
        time: dayjs().format('YYYY-MM-DD'),
        region: regionOptions.value[0]?.id || '',
        monitorId: monitoringPointOptions.value[0]?.id || ''
    })
    fetchAllData()
}

// 计算处理率
const getHandledRate = () => {
    if (warningData.totalCount === 0) return 0
    return Math.round((warningData.handledCount / warningData.totalCount) * 100)
}

// 图表配置 - 压力合格率饼图
const pressureRatioOption = computed(() => {
    const qualifiedCount = parseInt(qualifiedRateData.qualifiedSamplePointCount) || 0
    const unqualifiedCount = parseInt(qualifiedRateData.unqualifiedSamplePointCount) || 0
    const total = qualifiedCount + unqualifiedCount

    return {
        title: {
            text: '压力合格占比',
            left: 'center',
            textStyle: {
                fontSize: 14
            }
        },
        tooltip: {
            trigger: 'item',
            formatter: function(params) {
                const percent = total > 0 ? ((params.value / total) * 100).toFixed(1) : 0
                return `${params.name}: ${params.value} (${percent}%)`
            }
        },
        legend: {
            orient: 'horizontal',
            bottom: 0,
            data: ['合格', '不合格']
        },
        series: [
            {
                name: '压力合格率',
                type: 'pie',
                radius: ['40%', '70%'],
                avoidLabelOverlap: false,
                itemStyle: {
                    borderRadius: 10,
                    borderColor: '#fff',
                    borderWidth: 2
                },
                label: {
                    show: false
                },
                emphasis: {
                    label: {
                        show: true,
                        fontSize: 14,
                        fontWeight: 'bold'
                    }
                },
                labelLine: {
                    show: false
                },
                data: [
                    {
                        value: qualifiedCount,
                        name: '合格',
                        itemStyle: { color: '#36a3f7' }
                    },
                    {
                        value: unqualifiedCount,
                        name: '不合格',
                        itemStyle: { color: '#f4516c' }
                    }
                ]
            }
        ]
    }
})

// 图表配置 - 压力趋势图
const pressureTrendOption = computed(() => {
    const xAxisData = pressureTrendData.value.map(item => {
        if (searchForm.timeDimension === 1) {
            // 天维度，显示小时
            return dayjs(item.date).format('HH:mm')
        } else if (searchForm.timeDimension === 2) {
            // 月维度，显示日期
            return dayjs(item.date).format('MM-DD')
        } else {
            // 年维度，显示月份
            return dayjs(item.date).format('YYYY-MM')
        }
    })
    
    const seriesData = pressureTrendData.value.map(item => item.value)

    return {
        title: {
            text: '压力趋势',
            left: 'center',
            textStyle: {
                fontSize: 14
            }
        },
        tooltip: {
            trigger: 'axis',
            formatter: function(params) {
                return `${params[0].axisValue}<br/>压力: ${params[0].value} MPa`
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '15%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: xAxisData,
            axisLabel: {
            }
        },
        yAxis: {
            type: 'value',
            name: 'MPa'
        },
        series: [
            {
                name: '压力值',
                type: 'line',
                data: seriesData,
                smooth: true,
                symbol: 'circle',
                symbolSize: 6,
                itemStyle: {
                    color: '#36a3f7'
                },
                lineStyle: {
                    width: 3
                }
            }
        ]
    }
})

// 图表配置 - 压力振幅趋势图
const pressureFluctuationTrendOption = computed(() => {
    const xAxisData = amplitudeTrendData.value.map(item => {
        if (searchForm.timeDimension === 1) {
            return dayjs(item.date).format('HH:mm')
        } else if (searchForm.timeDimension === 2) {
            return dayjs(item.date).format('MM-DD')
        } else {
            return dayjs(item.date).format('YYYY-MM')
        }
    })
    
    const maxData = amplitudeTrendData.value.map(item => item.maxVal || 0)
    const minData = amplitudeTrendData.value.map(item => item.minVal || 0)
    const ampData = amplitudeTrendData.value.map(item => item.ampVal || 0)

    return {
        title: {
            text: '压力振幅趋势',
            left: 'center',
            textStyle: {
                fontSize: 14
            }
        },
        tooltip: {
            trigger: 'axis',
            formatter: function(params) {
                let result = `${params[0].axisValue}<br/>`
                params.forEach(param => {
                    result += `${param.marker} ${param.seriesName}: ${param.value} MPa<br/>`
                })
                return result
            }
        },
        legend: {
            data: ['最大压力', '最小压力', '压力振幅'],
            bottom: 0
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '15%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: xAxisData,
            axisLabel: {
            }
        },
        yAxis: {
            type: 'value',
            name: 'MPa'
        },
        series: [
            {
                name: '最大压力',
                type: 'line',
                smooth: true,
                symbol: 'circle',
                symbolSize: 6,
                data: maxData,
                itemStyle: {
                    color: '#f4516c'
                },
                lineStyle: {
                    width: 2
                }
            },
            {
                name: '最小压力',
                type: 'line',
                smooth: true,
                symbol: 'circle',
                symbolSize: 6,
                data: minData,
                itemStyle: {
                    color: '#34bfa3'
                },
                lineStyle: {
                    width: 2
                }
            },
            {
                name: '压力振幅',
                type: 'line',
                smooth: true,
                symbol: 'circle',
                symbolSize: 6,
                data: ampData,
                itemStyle: {
                    color: '#ffb822'
                },
                lineStyle: {
                    width: 2
                }
            }
        ]
    }
})

// 图表配置 - 告警分时段占比
const alertTimeOption = computed(() => {
    const xAxisData = alarmDistributionData.value.map(item => item.date)
    const seriesData = alarmDistributionData.value.map(item => item.value)

    return {
        title: {
            text: '告警分时段占比',
            left: 'center',
            textStyle: {
                fontSize: 14
            }
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            },
            formatter: function(params) {
                return `${params[0].axisValue}<br/>告警数: ${params[0].value}`
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '15%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: xAxisData,
            axisLabel: {
                rotate: 90
            }
        },
        yAxis: {
            type: 'value',
            name: '告警数'
        },
        series: [
            {
                name: '告警数',
                type: 'bar',
                data: seriesData,
                barWidth: '60%',
                itemStyle: {
                    color: '#f4516c'
                }
            }
        ]
    }
})

// 图表配置 - 告警趋势分析
const alertTrendOption = computed(() => {
    const xAxisData = alarmTrendData.value.map(item => {
        if (searchForm.timeDimension === 1) {
            return dayjs(item.date).format('HH:mm')
        } else if (searchForm.timeDimension === 2) {
            return dayjs(item.date).format('MM-DD')
        } else {
            return dayjs(item.date).format('YYYY-MM')
        }
    })
    
    const seriesData = alarmTrendData.value.map(item => item.value)

    return {
        title: {
            text: '告警趋势分析',
            left: 'center',
            textStyle: {
                fontSize: 14
            }
        },
        tooltip: {
            trigger: 'axis',
            formatter: function(params) {
                return `${params[0].axisValue}<br/>告警数: ${params[0].value}`
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '15%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: xAxisData,
            axisLabel: {
                rotate: 45
            }
        },
        yAxis: {
            type: 'value',
            name: '告警数'
        },
        series: [
            {
                name: '告警数',
                type: 'line',
                data: seriesData,
                smooth: true,
                symbol: 'circle',
                symbolSize: 6,
                itemStyle: {
                    color: '#f4516c'
                },
                lineStyle: {
                    width: 2
                }
            }
        ]
    }
})
</script>

<style scoped lang="scss">
.app-container {
    padding: 20px;
}

.search-form {
    margin-bottom: 0;
}

.title {
    font-size: 16px;
    font-weight: bold;
    text-align: center;
    margin-bottom: 15px;
}

.number {
    font-size: 32px;
    margin: 15px 0;
    color: #2563eb;
    font-weight: bold;
    text-align: center;
}

.puls {
    color: #666;
    text-align: center;
    font-size: 14px;
    margin-top: 8px;
    
    .msg {
        color: #999;
        margin-right: 8px;
    }
}

.statistics {
    display: flex;
    justify-content: space-around;
    margin: 20px 0;

    .item {
        text-align: center;

        .num {
            color: #dc2626;
            font-size: 28px;
            font-weight: bold;
            margin-bottom: 5px;
        }

        .num2 {
            color: #34bfa3;
        }

        .msg {
            color: #666;
            font-size: 14px;
        }
    }
}

.warning-levels {
    display: flex;
    justify-content: space-around;
    margin-top: 20px;

    .level-item {
        text-align: center;

        .level-tag {
            display: inline-block;
            padding: 4px 8px;
            border-radius: 4px;
            color: white;
            font-size: 12px;
            margin-bottom: 5px;

            &.level1 {
                background-color: #f4516c;
            }

            &.level2 {
                background-color: #ffb822;
            }

            &.level3 {
                background-color: #36a3f7;
            }
        }

        .level-count {
            font-size: 20px;
            font-weight: bold;
        }
    }
}

.mt-2 {
    margin-top: 20px;
}

:deep(.el-card) {
    margin-bottom: 0;
}

:deep(.el-table) {
    margin-top: 0;
}
</style>